package com.example.smartmedicalsystem.controller;

import com.example.smartmedicalsystem.DTO.ScheduleRequest;
import com.example.smartmedicalsystem.entity.*;
import com.example.smartmedicalsystem.repository.*;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {
    private final UserRepository userRepository;
    private final DoctorRepository doctorRepository;
    private final DepartmentRepository departmentRepository;
    private final ScheduleRepository scheduleRepository;
    private final MedicineRepository medicineRepository;
    private final CommentRepository commentRepository;
    private final PasswordEncoder passwordEncoder;
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/departments")
    public ResponseEntity<List<Department>> getAllDepartments() {
        return ResponseEntity.ok(departmentRepository.findAll());
    }
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/doctors/byDepartment")
    public ResponseEntity<?> getDoctorsByDepartment(@RequestParam Long departmentId) {
        Department dept = departmentRepository.findById(departmentId)
                .orElseThrow(() -> new RuntimeException("科室不存在"));
        return ResponseEntity.ok(doctorRepository.findByDepartment(dept));
    }
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/doctors")
    public ResponseEntity<?> addDoctor(@RequestBody Doctor doctor) {
        if (userRepository.findByUsername(doctor.getUser().getUsername()) != null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户名已存在");
        }
        User user = doctor.getUser();
        user.setRole(User.Role.DOCTOR);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        User savedUser = userRepository.save(user);
        doctor.setUser(savedUser);
        return ResponseEntity.ok(doctorRepository.save(doctor));
    }
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/schedules")
    public ResponseEntity<Schedule> createSchedule(@RequestBody ScheduleRequest request) {
        Doctor doctor = doctorRepository.findById(request.getDoctorId())
                .orElseThrow(() -> new RuntimeException("医生不存在"));

        Schedule schedule = new Schedule();
        schedule.setDoctor(doctor);
        schedule.setScheduleDate(request.getDate());
        schedule.setTimeSlot(request.getStartTime() + " - " + request.getEndTime()); // 合并时间段

        return ResponseEntity.ok(scheduleRepository.save(schedule));
    }

    @PostMapping("/medicines")
    public ResponseEntity<Medicine> addMedicine(@RequestBody Medicine medicine) {
        return ResponseEntity.ok(medicineRepository.save(medicine));
    }

    @GetMapping("/comments")
    public List<Comment> getAllComments() {
        return commentRepository.findAllByOrderByCreatedAtDesc();
    }

    @PutMapping("/comments/{id}/reply")
    public ResponseEntity<Comment> replyComment(
            @PathVariable Long id,
            @RequestParam String reply) {
        Comment comment = commentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("留言不存在"));
        comment.setReply(reply);
        return ResponseEntity.ok(commentRepository.save(comment));
    }

    @GetMapping("/doctors/schedules")
    public List<Doctor> getAllDoctorsWithSchedules() {
        // 直接调用自定义查询方法，一次性获取所有医生及其排班
        return doctorRepository.findAllWithSchedules();
    }
}